package com.xiaozeng.search.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaozeng.pojo.Product;
import com.xiaozeng.pojo.ProductDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: xiaozeng
 * @Date: 2022 11
 * @Description: 监听消息通知
 **/
@Component
public class RabbitMQListener {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 监听并插入数据
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "insert.queue"),//绑定的队列
            exchange = @Exchange("topic.ex"),//绑定的交换机
            key = "insert.product"//绑定的关键字
    ))
    public void insert(Product product) throws IOException {
        //新建一个product标签的数据，id是productId
        IndexRequest indexRequest = new IndexRequest("product")
                .id(product.getProductId().toString());
        //product转成ProductDoc
        ProductDoc productDoc = new ProductDoc(product);
        //productDoc转成JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String json  = objectMapper.writeValueAsString(productDoc);
        //插入JSON数据
        indexRequest.source(json, XContentType.JSON);
        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    }

    /**
     * 删除数据
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delete.queue"),
            exchange = @Exchange("topic.ex"),
            key = "delete.product"
    ))
    public void remove(Integer productId) throws IOException {
        //根据id删除数据
        DeleteRequest request = new DeleteRequest("product")
                .id(productId.toString());

        restHighLevelClient.delete(request,RequestOptions.DEFAULT);
    }
}
